// generateRoutes.ts
import React from "react";
import { lazy, ComponentType } from "react";
import { RouteObject } from "react-router-dom";
import LayoutIndex from "../layouts";
// 缓存扫描结果
let cachedRoutes: RouteObject[] | null = null;

// 扫描 pages 目录下所有 .tsx 文件
const pageFiles = import.meta.glob("../pages/**/*.tsx");

// 类型守卫，确保导入的模块是有效的 React 组件模块
function isComponentModule(
  module: unknown
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
): module is { default: ComponentType<any> } {
  return typeof module === "object" && module !== null && "default" in module;
}

// 生成路由配置
export const generateRoutes = (): RouteObject[] => {
  if (cachedRoutes) {
    return cachedRoutes;
  }
  const pageRoutes: RouteObject[] = [];
  for (const path in pageFiles) {
    // 将文件路径转换为路由路径
    const routePath = path
      .replace(/^\.\.\/pages\//, "") // 精确移除前缀
      .replace(/(\/index|page)?\.tsx$/, "") // 支持 Next.js 风格
      .replace(/(\w+)\/(\w+)/, "$1/$2") // 保留多级目录结构
      .replace(/\/$/, "") // 移除末尾斜杠
      .toLowerCase();
    // 动态导入组件
    const loadComponent = async () => {
      try {
        const module = await pageFiles[path]();
        if (isComponentModule(module)) {
          return module;
        }
        throw new Error(`Invalid module structure for ${path}`);
      } catch (error) {
        console.error(`Error loading component from ${path}:`, error);
        throw error;
      }
    };
    // 使用 lazy 实现代码分割
    const LazyComponent = lazy(loadComponent);
    console.log(routePath);
    pageRoutes.push({
      path: routePath === "" ? "/" : routePath,
      element: React.createElement(LazyComponent),
    });
  }
  const routes: RouteObject[] = [
    {
      path: "/",
      element: React.createElement(LayoutIndex),
      children: [
        ...pageRoutes,
        // 可在此添加公共子路由
      ],
    },
  ];
  cachedRoutes = routes;
  return routes;
};
